﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using WeifenLuo.WinFormsUI.Base;

namespace HRM
{
    public partial class FormTraining : FormBaseDataMstDtl
    {
        private DataSet mdsTrainingBas, mdsTrainingDtl;
        private SqlDataAdapter mdaTrainingBasUpdate, mdaTrainingDtlUpdate;
        private Ctrl_General mCtrlGeneral;
        private CurrencyManager mCurrencyManagerTraining;

        public FormTraining()
        {
            InitializeComponent();
        }

        protected override void BasicForm_Load(object sender, EventArgs e)
        {
            base.BasicForm_Load(sender, e);
        }

        protected override void BaseForm_Activated(object sender, System.EventArgs e)
        {
            base.BaseForm_Activated(sender, e);
        }

        protected override void BaseForm_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)
        {
            base.BaseForm_KeyDown(sender, e);
        }

        protected override void BasicForm_Closing(object sender, System.Windows.Forms.FormClosingEventArgs e)
        {
            base.BasicForm_Closing(sender, e);
        }

        protected override void LoadMasterData()
        {
            try
            {
                btnCancel = btncancel;
                btnOk = btnok;
                lblStatus = lblstatus;
                LoadData();
                LoadDataDetails(txtIDTraining.Text.Trim());
            }
            catch (Exception ex)
            {
                MessageBox.Show("Cannot open Training Management'. Error: " + ex.Message, ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Stop);
            }
        }

        #region LoadData
        private void LoadData()
        {
            try
            {
                Cursor = Cursors.WaitCursor;
                ClearDataBinding(this);
                if (mCtrlGeneral == null) mCtrlGeneral = new Ctrl_General();

                string ls_SQL = " Select ID_Training, Training_Name, Certificate, Begin_Date, End_Date, NumberOfAttended, Ex_Internal, PlaceOfTraining, ETD_IssueCertificate, Training_Fee, "
                    + "CreatedUser, UpdatedUser, CreatedDate, UpdatedDate From HRM_PersonnelTrainingBas ";

                mdsTrainingBas = mCtrlGeneral.GetSelect(ls_SQL, "HRM_PersonnelTrainingBas");
                mCtrlGeneral.GetAllData(out mdaTrainingBasUpdate, "HRM_PersonnelTrainingBas", " Order By Begin_Date ");

                if (mdsTrainingBas == null) return;
                //Binding: TextBox, Label
                txtIDTraining.DataBindings.Add(new Binding("Text", mdsTrainingBas.Tables[0], "ID_Training"));
                txtTrainingName.DataBindings.Add(new Binding("Text", mdsTrainingBas.Tables[0], "Training_Name"));
                txtCertificate.DataBindings.Add(new Binding("Text", mdsTrainingBas.Tables[0], "Certificate"));
                dtpStartDate.DataBindings.Add(new Binding("Text", mdsTrainingBas.Tables[0], "Begin_Date"));
                cboExInternal.DataBindings.Add(new Binding("Text", mdsTrainingBas.Tables[0], "Ex_Internal"));
                dtpEndDate.DataBindings.Add(new Binding("Text", mdsTrainingBas.Tables[0], "End_Date"));
                txtNOA.DataBindings.Add(new Binding("Text", mdsTrainingBas.Tables[0], "NumberOfAttended"));
                txtPOT.DataBindings.Add(new Binding("Text", mdsTrainingBas.Tables[0], "PlaceOfTraining"));
                dtpIssueCerETD.DataBindings.Add(new Binding("Text", mdsTrainingBas.Tables[0], "ETD_IssueCertificate"));
                //nudTrainingFee.DataBindings.Add(new Binding("Value", mdsTrainingBas.Tables[0], "Training_Fee"));

                mRowManager = (CurrencyManager)this.BindingContext[mdsTrainingBas.Tables[0]];
                // How to refresh the status of the row position?Ordinal_Number
                mRowManager.PositionChanged += new EventHandler(RowMaster_Changed);

                SetData2List(mdsTrainingBas);
                SetReadOnly(this, false);
                base.LoadMasterData();
                Cursor = Cursors.Default;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Cannot load header data'. Error: " + ex.Message, ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                Cursor = Cursors.Default;
            }
        }
        #endregion

        #region SetReadOnly
        private void SetReadOnly(Control aCtrl, bool abReadOnly)
        {
            foreach (Control lCtrl in aCtrl.Controls)
            {
                switch (lCtrl.GetType().ToString())
                {
                    case "System.Windows.Forms.TextBox":
                        ((TextBox)lCtrl).ReadOnly = !abReadOnly;
                        break;
                    case "System.Windows.Forms.DateTimePicker":
                        ((DateTimePicker)lCtrl).Enabled = abReadOnly;
                        break;
                    case "System.Windows.Forms.NumericUpDown":
                        ((NumericUpDown)lCtrl).Enabled = abReadOnly;
                        break;
                    case "System.Windows.Forms.ComboBox":
                        ((ComboBox)lCtrl).Enabled = abReadOnly;
                        break;
                }
            }
        }
        #endregion

        #region LoadDataDetails
        private void LoadDataDetails(string as_IDTraining)
        {
            try
            {
                Cursor = Cursors.WaitCursor;
                if (mCtrlGeneral == null) mCtrlGeneral = new Ctrl_General();

                string lCondition = " WHere TD.ID_Training = '" + as_IDTraining + "'" + " Order By TD.ID_Emp ";
                string lCondiction1 = " ID_Training = " + "'" + as_IDTraining + "'" + " Order By ID_Emp ";

                string ls_SQL = "Select TD.ID_Training, TD.ID_Emp, PF.Emp_NameVN, TD.Result, "
                    + " TD.CreatedUser, TD.UpdatedUser, TD.CreatedDate, TD.UpdatedDate  "
                    + " From HRM_PersonnelTrainingDtl TD inner join HRM_PersonalProfile PF on TD.ID_Emp = PF.ID_Emp "
                    + lCondition;

                mdsTrainingDtl = mCtrlGeneral.GetSelect(ls_SQL, "HRM_PersonnelTrainingDtl");
                mCtrlGeneral.GetDataWithCondition(out mdaTrainingDtlUpdate, "HRM_PersonnelTrainingDtl", lCondiction1);

                if (mdsTrainingDtl == null) return;

                mdbg_DetailGrid.DataSource = mdsTrainingDtl;
                mdbg_DetailGrid.DataMember = "HRM_PersonnelTrainingDtl";

                mdbg_DetailGrid.Columns["ID_Training"].Visible = false;

                mCurrencyManagerTraining = (CurrencyManager)mdbg_DetailGrid.BindingContext[mdsTrainingDtl, "HRM_PersonnelTrainingDtl"];
                mCurrencyManagerTraining.PositionChanged += new EventHandler(RowMaster_Changed);

                Cursor = Cursors.Default;
            }
            catch (Exception ex)
            {
                MessageBox.Show("Cannot load details data'. Error: " + ex.Message, ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                Cursor = Cursors.Default;
            }
        }
        #endregion

        #region Move Events
        public override void move_first()
        {
            base.move_first();
            if (GetCurrentAction() == MODES.ADD)
            {
                if (mdsTrainingDtl == null) LoadDataDetails(txtIDTraining.Text.Trim());
                AddDetails();
            }
            else
            {
                LoadDataDetails(txtIDTraining.Text.Trim());
                if (GetCurrentAction() == MODES.MODIFY) ModifyDetails();
            }
        }

        public override void move_last()
        {
            base.move_last();
            if (GetCurrentAction() == MODES.ADD)
            {
                if (mdsTrainingDtl == null) LoadDataDetails(txtIDTraining.Text.Trim());
                AddDetails();
            }
            else
            {
                LoadDataDetails(txtIDTraining.Text.Trim());
                if (GetCurrentAction() == MODES.MODIFY) ModifyDetails();
            }
        }

        public override void move_next()
        {
            base.move_next();
            if (GetCurrentAction() == MODES.ADD)
            {
                if (mdsTrainingDtl == null) LoadDataDetails(txtIDTraining.Text.Trim());
                AddDetails();
            }
            else
            {
                LoadDataDetails(txtIDTraining.Text.Trim());
                if (GetCurrentAction() == MODES.MODIFY) ModifyDetails();
            }
        }

        public override void move_previous()
        {
            base.move_previous();
            if (GetCurrentAction() == MODES.ADD)
            {
                if (mdsTrainingDtl == null) LoadDataDetails(txtIDTraining.Text.Trim());
                AddDetails();
            }
            else
            {
                LoadDataDetails(txtIDTraining.Text.Trim());
                if (GetCurrentAction() == MODES.MODIFY) ModifyDetails();
            }
        }
        #endregion

        #region add
        public override void add()
        {
            try
            {
                base.add();
                AddDetails();
                mRowManager.EndCurrentEdit();
                mRowManager.AddNew();
                SetReadOnly(this, true);
            }
            catch (Exception ex)
            {
                MessageBox.Show("Cannot add new Training. Error: " + ex.Message, ConstantKeys.Title);
            }
        }
        #endregion

        #region Add Details
        private void AddDetails()
        {
            if (mdsTrainingDtl != null) mdsTrainingDtl.Clear();
            mdbg_DetailGrid.Focus();
            mdbg_DetailGrid.AllowUserToAddRows = true;
            mdbg_DetailGrid.AllowUserToOrderColumns = false;
            mCurrencyManagerTraining.Position = mdsTrainingDtl.Tables[0].Rows.Count;
        }
        #endregion

        #region modify
        public override void modify()
        {
            base.modify();
            SetReadOnly(this, true);
            txtIDTraining.ReadOnly = true;
            ModifyDetails();
        }
        #endregion

        #region Modify details
        private void ModifyDetails()
        {
            mdbg_DetailGrid.Focus();
            mdbg_DetailGrid.AllowUserToAddRows = true;
            mdbg_DetailGrid.AllowUserToOrderColumns = false;
            mCurrencyManagerTraining.Position = mdsTrainingDtl.Tables[0].Rows.Count;
        }
        #endregion

        #region cancel
        public override void cancel()
        {
            if (mdsTrainingBas == null) return;
            mRowManager.EndCurrentEdit();
            mdsTrainingBas.RejectChanges();
            base.cancel();
            CancelDetails();
            SetReadOnly(this, false);
        }
        #endregion

        #region Cancel Details
        private void CancelDetails()
        {
            if (mdsTrainingDtl != null)
            {
                if (mdsTrainingDtl.Tables[0].Rows.Count > 0)
                {
                    mCurrencyManagerTraining.EndCurrentEdit();
                    mdsTrainingDtl.RejectChanges();
                }
                else
                    mdsTrainingDtl.Clear();
            }
            mdbg_DetailGrid.AllowUserToAddRows = false;
        }
        #endregion

        #region save
        public override void save()
        {
            mRowManager.EndCurrentEdit();
            if (mdsTrainingBas == null) return;
            if (txtIDTraining.Text.Trim().Equals(""))
            {
                MessageBox.Show("Cannot save Training data'. Error: Training ID. cannot empty.", ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                txtIDTraining.Focus();
                return;
            }

            DataRow dr = mdsTrainingBas.Tables[0].Rows[mRowManager.Position];
            if (dr.RowState == DataRowState.Modified)
            {
                dr["UpdatedUser"] = mMainForm.ms_UserID;
                dr["UpdatedDate"] = DateTime.Now;
            }
            else if (dr.RowState == DataRowState.Added)
            {
                dr["CreatedUser"] = mMainForm.ms_UserID;
                dr["CreatedDate"] = DateTime.Now;
            }

            string ls_ColName = "", ls_TableName = "";
            string ls_Error = mCtrlGeneral.Update(mdaTrainingBasUpdate, mdsTrainingBas, "HRM_PersonnelTrainingBas", out ls_ColName, out ls_TableName);
            if (ls_Error == "")
            {
                mdsTrainingBas.AcceptChanges();
                if (!SaveDetails()) return;
                if (GetCurrentAction() == MODES.ADD) LoadData();
                base.save();
                SetReadOnly(this, false);
            }
            else
                MessageBox.Show("Cannot save Training data'. Error: " + ls_Error, ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }
        #endregion

        #region Save Details
        private bool SaveDetails()
        {
            try
            {
                if (mdsTrainingBas == null || txtIDTraining.Text.Equals(""))
                {
                    mdbg_DetailGrid.AllowUserToAddRows = false;
                    mdbg_DetailGrid.AllowUserToOrderColumns = false;
                    return true;
                }
                if (mdsTrainingDtl.Tables[0].Rows.Count == 0)
                {
                    mdbg_DetailGrid.AllowUserToAddRows = false;
                    mdbg_DetailGrid.AllowUserToOrderColumns = false;
                    return true;
                }
                else
                {
                    DataRow ldr = mdsTrainingDtl.Tables[0].Rows[0];
                    if (ldr.RowState != DataRowState.Deleted)
                    {
                        if (ldr["ID_Training"].ToString() != "" && ldr["ID_Training"].ToString() != txtIDTraining.Text.Trim())
                        {
                            mdbg_DetailGrid.AllowUserToAddRows = false;
                            mdbg_DetailGrid.AllowUserToOrderColumns = false;
                            return true;
                        }
                    }
                    else
                    {
                        mdbg_DetailGrid.AllowUserToAddRows = false;
                        mdbg_DetailGrid.AllowUserToOrderColumns = false;
                    }
                }

                mCurrencyManagerTraining.EndCurrentEdit();

                if (!mdsTrainingDtl.HasChanges())
                {
                    mdbg_DetailGrid.AllowUserToAddRows = false;
                    mdbg_DetailGrid.AllowUserToOrderColumns = false;
                    return true;
                }

                DataSet ldsHasChanged = mdsTrainingDtl.GetChanges();
                foreach (DataRow dr in ldsHasChanged.Tables[0].Rows)
                {
                    if (dr.RowState == DataRowState.Deleted) continue;
                    //dr["Line_No"]	= 1;
                    if (dr.RowState == DataRowState.Added)
                    {
                        dr["ID_Training"] = txtIDTraining.Text.Trim();
                        dr["CreatedUser"] = mMainForm.ms_UserID;
                        dr["CreatedDate"] = DateTime.Now;
                    }
                    else if (dr.RowState == DataRowState.Modified)
                    {
                        dr["UpdatedUser"] = mMainForm.ms_UserID;
                        dr["UpdatedDate"] = DateTime.Now;
                    }
                }
                string ls_ColName = "", ls_TableName = "";
                string ls_Error = mCtrlGeneral.Update(mdaTrainingDtlUpdate, ldsHasChanged, "HRM_PersonnelTrainingDtl", out ls_ColName, out ls_TableName);
                if (ls_Error == "")
                {
                    mdsTrainingDtl.AcceptChanges();
                    LoadDataDetails(txtIDTraining.Text.Trim());
                    mdbg_DetailGrid.AllowUserToAddRows = false;
                    return true;
                }
                else
                {
                    MessageBox.Show("Cannot save Training details data'. Error: " + ls_Error, ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    return false;
                }
            }
            catch (SqlException ex)
            {
                MessageBox.Show("DB Error: " + ex.Message, ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Error);
                return false;
            }
        }
        #endregion

        #region delete
        public override void delete()
        {
            base.delete();
            if (!mb_AcceptDelete) return;
            if (!DeleteDetails()) return;
            DataSet ldsDelete = mdsTrainingBas;
            DataRow ldrDelete = ldsDelete.Tables[0].Rows[mRowManager.Position];
            int li_Pos = mRowManager.Position;
            ldrDelete.Delete();
            string lsColName = "", lsTableName = "";
            string lsReturnMessage = mCtrlGeneral.Update(mdaTrainingBasUpdate, ldsDelete, "HRM_PersonnelTrainingBas", out lsColName, out lsTableName);
            if (lsReturnMessage != "")
            {
                MessageBox.Show("Cannot delete Training data. Error: " + lsReturnMessage, ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                ldsDelete.RejectChanges();
                ldsDelete.AcceptChanges();
                mRowManager.Position = li_Pos;
                SetReadOnly(this, false);
                return;
            }
            //else
            //	DeleteTabPage();	//Delete TabPage
            base.post_delete();
            LoadDataDetails(txtIDTraining.Text.Trim());
            SetReadOnly(this, false);
        }
        #endregion

        #region Delete
        private bool DeleteDetails()
        {
            if (mdsTrainingDtl == null) return true;
            if (mdsTrainingDtl.Tables[0].Rows.Count == 0) return true;

            DataSet ldsDelete = (DataSet)mdbg_DetailGrid.DataSource;
            int i;
            for (i = 0; i < ldsDelete.Tables[0].Rows.Count; i++)
            {
                DataRow ldrDelete = ldsDelete.Tables[0].Rows[i];
                ldrDelete.Delete();
            }
            string lsColName = "", lsTableName = "";
            string lsReturnMessage = mCtrlGeneral.Update(mdaTrainingDtlUpdate, ldsDelete, "HRM_PersonnelTrainingDtl", out lsColName, out lsTableName);
            if (lsReturnMessage != "")
            {
                MessageBox.Show("Cannot delete Training details data. Error: " + lsReturnMessage, ConstantKeys.Title, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                ldsDelete.RejectChanges();
                ldsDelete.AcceptChanges();
                return false;
            }
            return true;
        }
        #endregion

        public override void SetListChanged()
        {
            LoadDataDetails(txtIDTraining.Text.Trim());
        }

        private void btnok_Click(object sender, System.EventArgs e)
        {
            save();
        }

        private void btncancel_Click(object sender, System.EventArgs e)
        {
            cancel();
        }

        public override void OpenSelection(string as_SelectioField)
        {
            SelectionParam lstr_param = new SelectionParam();
            lstr_param.ms_SelectionField = as_SelectioField;
            FormSelection lfrmSelect = new FormSelection();
            lfrmSelect.mfrmParentForm = this;
            lfrmSelect.Owner = mMainForm;

            switch (as_SelectioField)
            {
            
                case "ID_Emp":
                    lstr_param.ms_SelectionName = "Personnel Profile";
                    lfrmSelect.SetParam(lstr_param);
                    if (lfrmSelect.ShowDialog() == DialogResult.OK)
                    {
                        string[] astrID = lfrmSelect.GetParam().msa_ReturnValues[0].Split(',');
                        string[] astrName = lfrmSelect.GetParam().msa_ReturnValues[1].Split(',');
                        if (astrID.Length == 1)
                        {
                            mdbg_DetailGrid["ID_Emp", mdbg_DetailGrid.CurrentCell.RowIndex].Value = lfrmSelect.GetParam().msa_ReturnValues[0];
                            mdbg_DetailGrid["Emp_NameVN", mdbg_DetailGrid.CurrentCell.RowIndex].Value = lfrmSelect.GetParam().msa_ReturnValues[1];
                        }
                        else
                        {   // Assign first value for current row
                            mdbg_DetailGrid["ID_Emp", mdbg_DetailGrid.CurrentCell.RowIndex].Value = astrID[0];
                            mdbg_DetailGrid["Emp_NameVN", mdbg_DetailGrid.CurrentCell.RowIndex].Value = astrName[0];

                            // Assign next value for new row
                            DataRow dr;
                            DataSet ds = (DataSet)mdbg_DetailGrid.DataSource;
                            for (int i = 1; i < astrID.Length; i++)
                            {
                                dr = ds.Tables[0].NewRow();
                                dr["ID_Emp"] = astrID[i];
                                dr["Emp_NameVN"] = astrName[i];
                                ds.Tables[0].Rows.Add(dr);
                            }
                            mdbg_DetailGrid.DataSource = ds;
                            mdbg_DetailGrid.DataMember = "HRM_PersonnelTrainingDtl";
                        }

                    } break;

            }
        }

    }
}
